package net.hky365.lowcode.magic.interceptor;

import net.hky365.lowcode.magic.utils.LoggerHelper;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletResponse;
import org.ssssssss.script.MagicScriptContext;

@Component
public class ThrowableRequestInterceptor implements RequestInterceptor {

    /**
     * 接口执行完毕之后执行
     *
     * @param info        接口信息
     * @param context     脚本上下文
     * @param returnValue 即将要返回到页面的值
     * @param request     HttpServletRequest
     * @param response    HttpServletResponse
     * @param throwable   异常对象
     */
    @Override
    public void afterCompletion(ApiInfo info, MagicScriptContext context, Object returnValue, MagicHttpServletRequest request, MagicHttpServletResponse response, Throwable throwable) {
        Logger logger = LoggerHelper.getLogger(context);
        if (logger.isTraceEnabled()) {
            logger.trace("\n" +
                            "     apiInfo: {}\n" +
                            "magicContent: {}",
                    JSON.toJSONString(info),
                    JSON.toJSONString(context));
        }
        // 再抛出异常, 统一spring 处理得情况下, web 编辑器无法获取到异常日志, 通过此处输出日志,以便输出到web端
        if (throwable != null) {
            logger.error("执行请求出错, ", throwable);
        }
    }
}
